// 语音助手对象，支持文字转语音提示
export class VoiceHelper {
  constructor() {
    this.synth = window.speechSynthesis;
    this.hasSpoken = false;
  }

  speakOnce(text) {
    if (this.hasSpoken) return;
    this.hasSpoken = true;
    this.speak(text);
  }

  speak(text) {
    if (!this.synth) return;
    const utter = new window.SpeechSynthesisUtterance(text);
    utter.lang = 'zh-CN';
    this.synth.speak(utter);
  }

  reset() {
    this.hasSpoken = false;
  }

  // 新增：解锁语音播放，兼容浏览器自动播放策略
  unlock() {
    if (this.synth && this.synth.paused) {
      this.synth.resume();
    }
    // 兼容部分浏览器，主动播放一段无害短语，确保后续语音可用
    if (this.synth && !this.synth.speaking) {
      const utter = new window.SpeechSynthesisUtterance('语音已解锁');
      utter.lang = 'zh-CN';
      this.synth.speak(utter);
    }
  }
}
